package cn.znk.kedis.master_slave_model.template;

import cn.znk.kedis.master_slave_model.autoconfigure.RedisConfigureConstants;
import cn.znk.kedis.master_slave_model.exceptions.KedisConfigurationErrorException;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.lang.NonNull;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * IntelliJ IDEA
 * project: kedis-spring-boot-starter
 *
 * @author shimi
 * @version 1.0.0
 * @since 2021/11/22
 */
public class KedisTemplate<K, V> {

    private final RedisTemplate<K, V> w;

    private final RedisTemplate<K, V> r;

    private RedisTemplate<K, V> dynamic;

    static {
        InputStream in = KedisTemplate.class.getClassLoader().getResourceAsStream("META-INF/kedisbanner.txt");
        int read;
        try {
            while ((read = in.read()) != -1) {
                System.out.print((char) read);
            }
            System.out.println();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public KedisTemplate(RedisTemplate<K, V> w, RedisTemplate<K, V> r) {
        this.w = w;
        this.r = r;
    }

    public void setCache(K k, V v) throws KedisConfigurationErrorException {
        nonNullDataSource();
        dynamic.opsForValue().set(k, v);
    }

    public void setCache(K k, V v, long l, TimeUnit t) throws KedisConfigurationErrorException {
        nonNullDataSource();
        dynamic.opsForValue().set(k, v, l, t);
    }

    public Object getCache(K k) throws KedisConfigurationErrorException {
        nonNullDataSource();
        return dynamic.opsForValue().get(k);
    }

    public boolean delCache(K k) throws KedisConfigurationErrorException {
        nonNullDataSource();
        return dynamic.delete(k);
    }

    public ListOperations<K, V> wOpsForList() {
        return w.opsForList();
    }

    public ValueOperations<K, V> wOpsForValue() {
        return w.opsForValue();
    }

    public ListOperations<K, V> rOpsForList() {
        return r.opsForList();
    }

    public ValueOperations<K, V> rOpsForValue() {
        return r.opsForValue();
    }

    public void setDynamic(@NonNull RedisTemplate<K, V> dynamic) {
        this.dynamic = dynamic;
    }

    public RedisTemplate<K, V> getW() {
        return w;
    }

    public RedisTemplate<K, V> getR() {
        return r;
    }

    private void nonNullDataSource() throws KedisConfigurationErrorException {
        if (dynamic == null) {
            String ERROR_MESSAGE = "请开启动态数据源配置项 : {" + RedisConfigureConstants.GLOBAL_CONFIGURE_PREFIX + ".enable-dynamic = true" + "}";
            throw new KedisConfigurationErrorException(ERROR_MESSAGE);
        }
    }

}
